import { Config } from 'config.js';

class Token {
  constructor() {
    this.verifyUrl = Config.restUrl + 'token/verify';
    this.tokenUrl = Config.restUrl + 'token/user';
  }

  /**
   * 对token进行判断
   */
  verify() {
    var token = wx.getStorageSync('token');
    if (!token) {
      this.getTokenFromServer();
    }else{
      this._verifyFromServer(token);
    }
  }

  /**
   * 验证token是否合法
   */
  _verifyFromServer(token){
    var that = this;
    wx.request({
      url: that.verifyUrl,
      method:'POST',
      data:{
        token:token
      },
      success:function(res){
        var valid = res.data.isValid;
        // 如果token不合法，重新从后台获取token
        if(!valid){
          that.getTokenFromServer();
        }
      }
    })
  }

  /**
   * 从服务器获取token
   */
  getTokenFromServer(callBack) {
    var that = this;
    // 微信登录接口
    wx.login({
      success: function (res) {
        // 从后台获取token并存储
        wx.request({
          url: that.tokenUrl,
          method:'POST',
          data:{
            code:res.code
          },
          success:function(res){
            wx.setStorageSync('token', res.data.token);
            callBack && callBack(res.data.token);
          }
        })
      }
    })
  }
}

export {Token};